package com.zhiqianbao.activity;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserAttachment;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.File2Code;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/5.
 */
public class TakeAccesssoryPicActivity extends BaseActivity {
    private static final String TAG = TakeAccesssoryPicActivity.class.getSimpleName();
    /**
     * 附件标题
     */
    EditText edittextAccessoryPicContent;
    /**
     * 附件上传按钮
     */
    ImageView imageViewTakeAccessoryPic;
    /**
     * 是否存在图片
     */
    boolean isPic;
    /**
     * 上传类型
     */
    String type;
    /**
     * 确认按钮
     */
    Button buttonSubmitAccessoryOK;
    /**
     * 原因显示
     */
    RelativeLayout relativePassStatusReason;
    /**
     * 原因内容
     */
    TextView textviewPassStatusReasonTitle;
    /**
     *
     */
    TextView TextViewPassStatusReason;
    /**
     * 是否通过审核 false 未通过  true通过
     */
    boolean isChecked;
    /**
     * 是否编辑 false 增加 true 编辑
     */
    boolean isEdit;
    boolean isClick = false;
    /**
     * 图片路径
     */
    String currentImagePath;
    Bitmap photo;
    Long userAttachmentId;
    UserAttachment userAttachment;
    /**
     * 缓存
     */
    String currentImagePathTemp;

    ImageLoader imageLoader = ImageLoader.getInstance();


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RESULT_OK:
                    userAttachment = (UserAttachment) msg.obj;
                    if(userAttachment!=null) {
                        currentImagePath = userAttachment.getCachePath();
                    /*photo = File2Code.getBitmap(currentImagePath, TakeAccesssoryPicActivity.this);
                    if (photo != null) {
                        imageViewTakeAccessoryPic.setImageBitmap(photo);
                    }*/
                        imageLoader.displayImage("file://" + currentImagePath, imageViewTakeAccessoryPic);
                    }
                    break;
                default:
                   // showShortToast("图片请求失败，请检查网络状况");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_takeaccessory_pic);
        init();
        initView();
    }

    private void initView() {
         edittextAccessoryPicContent=(EditText)findViewById(R.id.edittext_accessoryPic_content);
         imageViewTakeAccessoryPic=(ImageView)findViewById(R.id.imageView_takeAccessory_Pic);
         buttonSubmitAccessoryOK=(Button)findViewById(R.id.button_submitAccessory_OK);
         relativePassStatusReason=(RelativeLayout)findViewById(R.id.relative_pass_status_reason);
         textviewPassStatusReasonTitle=(TextView)findViewById(R.id.textview_pass_status_reason_title);
         TextViewPassStatusReason=(TextView)findViewById(R.id.TextView_pass_status_reason);

        imageLoader.init(ImageLoaderConfiguration.createDefault(this));

        Intent intent = getIntent();
        userAttachment = (UserAttachment) intent.getSerializableExtra("userAttachment");
        userAttachmentId = (Long) intent.getSerializableExtra("userAttachmentId");
        //编辑或查看
        if (userAttachment != null) {
            isEdit = true;
            isPic = true;
            //从缓存中取照片
            UserAttachment cacheUserAttachment = userAttachment.findById(UserAttachment.class, userAttachmentId);

            if (cacheUserAttachment!= null && cacheUserAttachment.getCachePath() != null) {
                currentImagePath = cacheUserAttachment.getCachePath();
                //photo = File2Code.getBitmap(currentImagePath, TakeAccesssoryPicActivity.this);
                photo = imageLoader.loadImageSync("file://" + currentImagePath);
                if (photo == null) {
                    updateWeather(cacheUserAttachment.getUrl());
                } else {
                    imageLoader.displayImage("file://" + currentImagePath, imageViewTakeAccessoryPic);
                    //imageViewTakeAccessoryPic.setImageBitmap(photo);
                }
            //远程加载图片
            } else {
                updateWeather(userAttachment.getUrl());
            }
            edittextAccessoryPicContent.setText(userAttachment.getTitle());
            //未审核
            if (Constants.USER_AUDIT_STATE_NO.equals(userAttachment.getState())) {
                relativePassStatusReason.setVisibility(View.GONE);
                isChecked = false;
            //未通过
            } else if (Constants.USER_AUDIT_STATE_FAILED.equals(userAttachment.getState())) {
                //显示原因
                TextViewPassStatusReason.setText(userAttachment.getFeedback());
                relativePassStatusReason.setVisibility(View.VISIBLE);
                isChecked = false;
            //已通过
            } else if (Constants.USER_AUDIT_STATE_SUCCESS.equals(userAttachment.getState())){
                relativePassStatusReason.setVisibility(View.GONE);
                isChecked = true;
            }

            //title 不可编辑
            if ("0".equals(userAttachment.getTitleReadonly())) {
                edittextAccessoryPicContent.setCursorVisible(false);      //设置输入框中的光标不可见
                edittextAccessoryPicContent.setFocusable(false);           //无焦点
                edittextAccessoryPicContent.setFocusableInTouchMode(false);
            } else {
                edittextAccessoryPicContent.setCursorVisible(true);      //设置输入框中的光标不可见
                edittextAccessoryPicContent.setFocusable(true);           //无焦点
                edittextAccessoryPicContent.setFocusableInTouchMode(true);
            }


            //新增
        } else {
            isEdit = false;
            isPic = false;
        }

        ButtonListener listener = new ButtonListener();
        imageViewTakeAccessoryPic.setOnClickListener(listener);
        buttonSubmitAccessoryOK.setOnClickListener(listener);

    }


    private void showPhotoDialog(final ImageView imageView) {
        final List<String> menus = new ArrayList<>();

        if (!isChecked) {
            if (isEdit) {
                menus.add("拍照上传");
                menus.add("预览大图");
            } else {
                //如果存在图片 显示预览大图功能
                if (isPic) {
                    menus.add("预览大图");
                }
                menus.add("拍照上传");
            }
            menus.add("手机相册");
        } else {
            menus.add("预览大图");
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(TakeAccesssoryPicActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_bank_one, null);
        TextView title = (TextView) view.findViewById(R.id.textview_bank_title);
        title.setText("选择图片位置");
        ListView listView = (ListView) view.findViewById(R.id.listView_bank);
        //修改高度
        final ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = ActionBar.LayoutParams.WRAP_CONTENT;
        listView.setLayoutParams(params);
        listView.setAdapter(new ArrayAdapter<String>(TakeAccesssoryPicActivity.this, android.R.layout.simple_list_item_1, menus));
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        dialog.show();
        //弹出框绑定方法
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (menus.get(position)) {
                    case "重新上传":
                    case "拍照上传":
                        getImageFromCamera();
                        isClick = true;
                        break;
                    case "预览大图" :
                        Intent bigPicIntent = new Intent(TakeAccesssoryPicActivity.this, BigPicDialogActivity.class);
                        bigPicIntent.putExtra("bitmap", currentImagePath);
                        startActivity(bigPicIntent);
                        break;
                    case "手机相册" :
                        isClick = true;
                        getImageFromGallery();
                        break;
                }
                dialog.cancel();
            }
        });
        //关闭弹出框按钮
        TextView button = (TextView) view.findViewById(R.id.bank_dialog_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(R.id.imageView_takeAccessory_Pic==v.getId()) {
                    showPhotoDialog(imageViewTakeAccessoryPic);
            }
            else if(R.id.button_submitAccessory_OK==v.getId()){
                    if (StringUtils.isBlank(currentImagePath)) {
                        showShortToast1("请添加附件");
                        return;
                    }
                    if (StringUtils.isBlank(edittextAccessoryPicContent.getText().toString())) {
                        showShortToast1("请填写附件标题");
                        return;
                    }

                    Map<String, String> param = new HashMap<>();
                    param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    param.put("token",  Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    param.put("title", edittextAccessoryPicContent.getText().toString());
                    param.put("type", type);
                    if (userAttachmentId != null) {
                        if (!isClick) {
                            showShortToast1("请重新上传附件");
                            return;
                        }
                        param.put("id", userAttachmentId.toString());
                    }
                    new SaveUserAttrachmentAsyncTask().execute(param);
            }
        }
    }

    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
            currentImagePathTemp = FileUtils.getPhotopath();
            Uri uri = Uri.fromFile(new File(currentImagePathTemp));
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(getImageByCamera, Constants.REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            showShortToast1("请确认已经插入SD卡");
        }
    }

    protected void getImageFromGallery () {
        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK) {
            return;
        }
        ImageSize targetSize = new ImageSize(160, 100);
        switch (requestCode) {
            case Constants.REQUEST_CODE_CAPTURE_CAMEIA:
                Log.i(this.getClass().toString(), "拍照返回");
                currentImagePath = currentImagePathTemp;
                imageLoader.displayImage("file://" + currentImagePath, imageViewTakeAccessoryPic, targetSize);
                isPic = true;
                type = "拍照";
                break;
            case 3 :
                Log.i(this.getClass().toString(), "相册返回");
                Uri selectedImage = data.getData();
                String path = selectedImage.getPath();
                Log.i(TAG, path);
                //小米
                if (path.indexOf(".") != -1) {
                    currentImagePath = path;
                } else {
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    currentImagePath = cursor.getString(columnIndex);
                    Log.d(TAG, currentImagePath);
                    cursor.close();
                }
                imageLoader.displayImage("file://" + currentImagePath, imageViewTakeAccessoryPic, targetSize);
                isPic = true;
                type = "相册";
                break;
        }
    }

    private class SaveUserAttrachmentAsyncTask extends AsyncTask<Map, Void, Result<UserAttachment>> {
        @Override
        protected Result<UserAttachment> doInBackground(Map... params) {
            Bitmap bitmap = imageLoader.loadImageSync("file://" + currentImagePath);
            String voucherPic = File2Code.bitmapToBase64(bitmap, 500);
            if (!TextUtils.isEmpty(voucherPic)){
                params[0].put("base64Str", voucherPic);
            }
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/editUserAttachment", params[0], TakeAccesssoryPicActivity.this);
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<UserAttachment> resultObject = Result.fromJson(result, UserAttachment.class);
            return resultObject;
        }
        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }
        @Override
        protected void onPostExecute(Result<UserAttachment> result) {
            if(result == null) {
                showShortToast1("连接超时！");
            } else {
                //请求成功
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    UserAttachment userAttachment = result.getData();
                    /**
                     * 释放图片资源
                     */
                    recycleBitmap(photo);

                    userAttachment.setCachePath(currentImagePath);
                    userAttachment.save();

                    Intent intent = new Intent();
                    TakeAccesssoryPicActivity.this.setResult(RESULT_OK, intent);
                    TakeAccesssoryPicActivity.this.finish();

                } else {
                    showShortToast1(result.getMsg());
                }
            }
            closeWaitDialog();
        }
    }

    private void updateWeather(final String url) {
        new Thread(new Runnable(){
            @Override
            public void run() {
                //需要数据传递，用下面方法；
                Message msg = new Message();
                //远程加载图片
                Bitmap pic = imageLoader.loadImageSync(url);
                if (pic == null) {
                    msg.what = RESULT_CANCELED;
                } else {

                    //得到缓存路径
                    String cachePath = FileUtils.getPhotopath();
                    FileUtils.bitmap2file(cachePath, pic);
                    userAttachment.setCachePath(cachePath);
                    userAttachment.setId(userAttachmentId);
                    //缓存到本地
                    userAttachment.save();
                    //耗时操作，完成之后发送消息给Handler，完成UI更新；

                    msg.what = RESULT_OK;
                    msg.obj = userAttachment;//可以是基本类型，可以是对象，可以是List、map等；
                }
                mHandler.sendMessage(msg);
            }
        }).start();
    }
}
